package core

import (
	c "cat_mouse/core/controllers"
	"cat_mouse/core/middlewares"
	infraMw "cat_mouse/infra/middlewares"
	"cat_mouse/infra/validators"
	"github.com/arl/statsviz"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

func init() {
	// 自定义验证器的注册
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		if err := v.RegisterValidation("no_blank", validators.NotAllowBlank); err != nil {
			panic(err)
		}
		if err := v.RegisterValidation("no_side_blank", validators.NotAllowSideBlank); err != nil {
			panic(err)
		}
	}
}

func InitRouter() *gin.Engine {
	router := gin.New()
	// 集成statsviz监控
	router.GET("/debug/statsviz/*filepath", func(context *gin.Context) {
		if context.Param("filepath") == "/ws" {
			statsviz.Ws(context.Writer, context.Request)
			return
		}
		statsviz.IndexAtRoot("/debug/statsviz").ServeHTTP(context.Writer, context.Request)
	})

	router.GET("/api/v1/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"status": "200",
			"msg":    "success",
			"data":   nil,
		})
	})

	// 要在路由组之前全局使用「跨域中间件」, 否则OPTIONS会返回404
	router.Use(infraMw.Cors(), middlewares.Auth(), infraMw.Recover)

	//validCodeGroup := router.Group("/api/v1/validCode")
	//{
	//	c.ValidCodeControllerRegister(validCodeGroup)
	//}

	userGroup := router.Group("/api/v1/users")
	{
		c.UserControllerRegister(userGroup)
	}

	roomGroup := router.Group("/api/v1/rooms")
	{
		c.RoomControllerRegister(roomGroup)
	}
	return router
}
